package com.zmn.oms.third.youzan;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.oms.common.utils.HttpUtil;
import com.zmn.oms.third.base.dto.api.ApiInvokResult;
import com.zmn.oms.third.youzan.api.OrderClue;
import com.zmn.oms.third.youzan.api.TokenData;
import com.zmn.oms.third.youzan.api.YouzanResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 类描述：
 *
 * @author lhl
 * @date 2020/05/27 19:53
 */
@Slf4j
public class YouzanApiInvoker {

    private static String TOKEN_TEMPLETE = "{\"authorize_type\":\"silent\",\"client_id\":\"%s\",\"client_secret\":\"%s\",\"grant_id\":\"%s\",\"refresh\":true}";

    /**
     * 获取token
     * @param shopId
     * @return
     */
    public static ApiInvokResult<TokenData> getToken(String shopId) {
        String params = String.format(TOKEN_TEMPLETE, YouzanConsts.CLIENT_ID, YouzanConsts.CLIENT_SECRET, shopId);

        ApiInvokResult<TokenData> result = new ApiInvokResult();
        try {
            log.info("【{}】API-Request-获取Token：grantId=[{}]", YouzanConsts.CHANNEL_NAME, shopId);
            String response = HttpUtil.httpsPost(YouzanConsts.TOKEN_URL, params);
            log.info("【{}】API-Response-获取Token：result=[{}]", YouzanConsts.CHANNEL_NAME, response);

            YouzanResponse<TokenData> tokenResponse = JSON.parseObject(
                    response, new TypeReference<YouzanResponse<TokenData>>() {});

            if (tokenResponse.getSuccess() != null) {
                result.setSuccess(tokenResponse.getSuccess());
                result.setData(tokenResponse.getData());
                result.setMsg(tokenResponse.getMessage());
            }
            else if (tokenResponse.getGwErrResp() != null) {
                result.setSuccess(false);
                result.setMsg(tokenResponse.getGwErrResp().getErrMsg());
                result.setCode(tokenResponse.getGwErrResp().getErrCode());
            }
        } catch (Exception e) {
            log.error(String.format("【%s】API-调用失败: %s", YouzanConsts.CHANNEL_NAME, e.getMessage()), e);

            result.setSuccess(false);
            result.setMsg(e.getMessage());
        }

        return result;
    }

    /**
     * 获取订单数据
     * @param token
     * @return
     */
    public static ApiInvokResult<OrderClue> getOrderClues(String token) {
        String url = (YouzanConsts.API_URL + YouzanConsts.API_METHOD_PULL_CLUES +"?access_token="+ token);

        ApiInvokResult<OrderClue> result = new ApiInvokResult();
        try {
            Map<String, String> params = new HashMap<>();
            Date now = new Date();
            params.put("start_created", DateUtil.toString(now, "yyyy-MM-dd 00:00:00"));
            params.put("end_created", DateUtil.toString(now, "yyyy-MM-dd 23:59:59"));

            String content = JSON.toJSONString(params);

            log.info("【{}】API-Request-拉取线索：token=[{}], params=[{}]", YouzanConsts.CHANNEL_NAME, token,
                    JSON.toJSONString(content));
            String response = HttpUtil.httpsPost(url, content);
            log.info("【{}】API-Response-拉取线索：result=[{}]", YouzanConsts.CHANNEL_NAME, response);

            YouzanResponse<OrderClue> tokenResponse = JSON.parseObject(
                    response, new TypeReference<YouzanResponse<OrderClue>>() {});

            if (tokenResponse.getSuccess() != null) {
                result.setSuccess(tokenResponse.getSuccess());
                result.setData(tokenResponse.getData());
                result.setMsg(tokenResponse.getMessage());
            }
            else if (tokenResponse.getGwErrResp() != null) {
                result.setSuccess(false);
                result.setMsg(tokenResponse.getGwErrResp().getErrMsg());
                result.setCode(tokenResponse.getGwErrResp().getErrCode());
            }
        } catch (Exception e) {
            log.error(String.format("【%s】API-调用失败: %s", YouzanConsts.CHANNEL_NAME, e.getMessage()), e);

            result.setSuccess(false);
            result.setMsg(e.getMessage());
        }

        return result;
    }

    /**
     * 获取订单详情
     * @param token
     * @param tid 有赞订单号，E开头长度24位字母和数字组合
     * @return
     */
    public static ApiInvokResult<OrderClue.FullOrderInfoList> getOrderDetail(String token, String tid) {
        String url = (YouzanConsts.API_URL + YouzanConsts.API_METHOD_ORDER_DETAIL +"?access_token="+ token);

        ApiInvokResult<OrderClue.FullOrderInfoList> result = new ApiInvokResult();
        try {
            String content = String.format("{\"tid\":\"%s\"}", tid);

            log.info("【{}】API-Request-查询订单详情：params=[{}]", YouzanConsts.CHANNEL_NAME, JSON.toJSONString(content));
            String response = HttpUtil.httpsPost(url, content);
            log.info("【{}】API-Response-查询订单详情：result=[{}]", YouzanConsts.CHANNEL_NAME, response);

            YouzanResponse<OrderClue.FullOrderInfoList> tokenResponse = JSON.parseObject(
                    response, new TypeReference<YouzanResponse<OrderClue.FullOrderInfoList>>() {});

            if (tokenResponse.getSuccess() != null) {
                result.setSuccess(tokenResponse.getSuccess());
                result.setData(tokenResponse.getData());
                result.setMsg(tokenResponse.getMessage());
            }
            else if (tokenResponse.getGwErrResp() != null) {
                result.setSuccess(false);
                result.setMsg(tokenResponse.getGwErrResp().getErrMsg());
                result.setCode(tokenResponse.getGwErrResp().getErrCode());
            }
        } catch (Exception e) {
            log.error(String.format("【%s】API-调用失败: %s", YouzanConsts.CHANNEL_NAME, e.getMessage()), e);

            result.setSuccess(false);
            result.setMsg(e.getMessage());
        }

        return result;
    }

    public static void main(String[] args) {
        String response = "{\"gw_err_resp\":{\"err_msg\":\"Token 不存在\",\"err_code\":4203}}";
        try {
            YouzanResponse<OrderClue> youzanResponse = JSON.parseObject(
                    response, new TypeReference<YouzanResponse<OrderClue>>() {
            });
            System.out.println(JSON.toJSONString(youzanResponse));
        } catch (Exception e) {
            System.out.println(e.getClass().getSimpleName());
        }


    }
}
